package com.example.demo.excel.service.impl;

import com.example.demo.excel.db.entity.BaseTeacherInfo;
import com.example.demo.excel.db.repository.BaseTeacherInfoRepository;
import com.example.demo.excel.service.BaseTeacherService;
import com.example.demo.excel.service.ColumnTitleMap;
import com.example.demo.excel.service.ImportExcelBaseService;
import com.example.demo.excel.util.ExcelUtil;
import com.example.demo.excel.util.ExportExcelUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * @author zjq
 * @version 创建时间：2021-12-17 9:12:54
 */

@Service
public class BaseTeacherServiceImpl extends ImportExcelBaseService implements BaseTeacherService {


    @Autowired
    ExportExcelUtil exportExcelUtil;
    @Autowired
    private BaseTeacherInfoRepository baseTeacherInfoRepository;

    @Override
    public void exportTemplate(HttpServletRequest req, HttpServletResponse resp) {
        try {

            // fileName Excel文件名称 ----名称中文的会乱码，前端写死覆盖名称
            String fileName = "teacherInfo" + System.currentTimeMillis();

            // handers Excel列标题(数组)
            String[] header = {"*学校名称", "*姓名", "*手机号码", "性别", "时间"};

            // downData 下拉框数据(数组)
            List<String[]> list = new ArrayList<String[]>();
            // downRows 下拉列的序号(数组,序号从0开始)
            List<Integer> listi = new ArrayList<Integer>();

            String text = "填表说明：\r\n" + "1、红色部分为必填，请您务必填写；\r\n" + "2、绿色部分为选填项，您可以根据用户信息酌情填写；\r\n"
                    + "3、为了您顺利、准确导入数据请使用网站导出的原始模板。";

            // listred 需加红的列
            List<Integer> listred = new ArrayList<Integer>();
            listred.add(0);
            listred.add(1);
            listred.add(2);

            // textRows 需转换为text格式的列 ----身份证手机号之类的需要
            List<Integer> textRows = new ArrayList<Integer>();
            textRows.add(3);

            // 学校名称---具有下拉框
            List<String> xxmcList = new ArrayList<String>();

            // 可以替换成查询出来的某个list
            xxmcList.add("第一学校");
            xxmcList.add("第二学校");
            xxmcList.add("第三学校");

            String[] xxmc = xxmcList.toArray(new String[xxmcList.size()]);
            list.add(xxmc);
            listi.add(0);

            // 性别
            List<String> keySetxb = new ArrayList<String>();
            keySetxb.add("男");
            keySetxb.add("女");
            String[] xingbie = keySetxb.toArray(new String[keySetxb.size()]);
            list.add(xingbie);
            listi.add(3);

            ExcelUtil.createExcelTemplate(resp, fileName, header, list, listi, text, listred, textRows);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Transactional
    @Override
    public Map<String, List<BaseTeacherInfo>> importExcelTeacherinfo(MultipartFile file) {

        Map<String, List<BaseTeacherInfo>> map = new HashMap<String, List<BaseTeacherInfo>>();

        int rowNum = 0;// 已取值的行数s
        int colNum = 0;// 列号
        int realRowCount = 0;// 真正有数据的行数
        // 得到工作空间
        Workbook workbook = null;

        try {
            workbook = super.getWorkbookByInputStream(file.getInputStream(), file.getOriginalFilename());
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 得到工作表
        Sheet sheet = super.getSheetByWorkbook(workbook, 0);
        if (sheet.getRow(20000) != null) {
            throw new RuntimeException("单批次导入必须小于或等于20000行！");
        }
        realRowCount = sheet.getPhysicalNumberOfRows();//读取所有行

        List<BaseTeacherInfo> liste = new ArrayList<>();

        Date date = new Date();

        for (Row row : sheet) {
            if (realRowCount == rowNum) {
                break;
            }
            if (super.isBlankRow(row)) {// 空行跳过
                continue;
            }
            if (row.getRowNum() == -1) {
                continue;
            } else {
                if (row.getRowNum() == 0 || row.getRowNum() == 1) {// 表头跳过
                    continue;
                }
            }
            rowNum++;
            colNum = 0;

            BaseTeacherInfo baseTeacherinfo = new BaseTeacherInfo();
            String errorMsg = "";

            // 学校名称
            String schoolName = super.getCellValue(sheet, row, colNum);
            if (StringUtils.isEmpty(schoolName)) {
                errorMsg += "学校名称不能为空";
            } else {
                baseTeacherinfo.setSchoolName(schoolName);
            }

            // 设置姓名
            String name = super.getCellValue(sheet, row, ++colNum);
            if ("".equals(name)) {
                if (!"".equals(errorMsg)) {
                    errorMsg += ",";
                }
                errorMsg += "姓名不能为空";
            } else if (name.length() > 32) {
                if (!"".equals(errorMsg)) {
                    errorMsg += ",";
                }
                errorMsg += "姓名过长";
            } else {
                baseTeacherinfo.setName(name);
            }

            // 设置手机号码
            String mobile = super.getCellValue(sheet, row, ++colNum);
            if (StringUtils.isEmpty(mobile)) {
                if (!"".equals(errorMsg)) {
                    errorMsg += ",";
                }
                errorMsg += "手机号码不能为空";
            } else if (mobile.length() > 11) {
                if (!"".equals(errorMsg)) {
                    errorMsg += ",";
                }
                errorMsg += "手机号码过长";
            } else {
                baseTeacherinfo.setMobile(mobile);
            }

            // 设置性别
            String sex = super.getCellValue(sheet, row, ++colNum);
            if (StringUtils.isNotEmpty(sex)) {
                if ("男".equals(sex)) {
                    baseTeacherinfo.setSex("1");
                } else if ("女".equals(sex)) {
                    baseTeacherinfo.setSex("0");
                } else {
                    baseTeacherinfo.setSex("2");
                }
            }

            // 没有错误信息可以保存
            if ("".equals(errorMsg)) {
                baseTeacherinfo.setCreateTime(date);
                baseTeacherinfo.setUpdateTime(date);
                baseTeacherInfoRepository.save(baseTeacherinfo);
            } else {

                // 错误信息需要记录
                baseTeacherinfo.setSchoolName(schoolName);
                baseTeacherinfo.setName(name);
                baseTeacherinfo.setSex(sex);
                baseTeacherinfo.setMobile(mobile);
                baseTeacherinfo.setErrorMsg(errorMsg);
                liste.add(baseTeacherinfo);
            }

        }
        map.put("liste", liste);
        return map;
    }

    @Override
    public void exportTeacherinfo(String fileName, List<BaseTeacherInfo> list, HttpServletResponse resp) {
        try {
            ArrayList<String> titleKeyList = new ColumnTitleMap("teacherinfoe").getTitleKeyList();
            Map<String, String> titleMap = new ColumnTitleMap("teacherinfoe").getColumnTitleMap();
            List<Map<String, Object>> src_list = new ArrayList<Map<String, Object>>();
            for (int i = 0; i < list.size(); i++) {
                Map<String, Object> map = new HashMap<String, Object>();
                BaseTeacherInfo bt = list.get(i);
                map.put("schoolName", bt.getSchoolName());// 学校名称
                map.put("name", bt.getName());// 姓名
                map.put("mobile", bt.getMobile());// 手机号
                map.put("sex", bt.getSex());// 性别

                map.put("errorMsg", bt.getErrorMsg());
                src_list.add(map);
            }
            exportExcelUtil.expoerDataExcel(resp, titleKeyList, titleMap, src_list, fileName);
        } catch (Exception e) {
            System.out.println("Exception: " + e.toString());
        }

    }

}
